import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  // token 代表登录状态
  const token = ref<string | null>(null)
  const username = ref<string | null>(null)
  // 存储当前密码，初始值为默认密码
  const currentPassword = ref('huang137')

  // 简单模拟登录，实际应调用后端API
  function login(account: string, password: string) {
    if (account === '22001010905' && password === currentPassword.value) {
      token.value = 'mock-token-123456'
      username.value = account
      return true
    } else {
      return false
    }
  }

  function logout() {
    token.value = null
    username.value = null
    // 强制刷新页面，确保所有状态重置
    window.location.reload()
  }

  // 重置密码方法
  function resetPassword(account: string, newPassword: string) {
    // 这里仅做演示，实际应该调用后端API
    if (account === '22001010905') {
      // 更新存储的密码
      currentPassword.value = newPassword
      // 确保退出登录状态
      token.value = null
      username.value = null
      return true
    }
    return false
  }

  return { token, username, login, logout, resetPassword }
}, {
  persist: true // 持久化
}) 